package org.zoomdev.zoom.dao.impl;

import org.zoomdev.zoom.dao.Dao;
import org.zoomdev.zoom.dao.Entity;
import org.zoomdev.zoom.dao.utils.DaoUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

public class BatchExecutor {


    public static int[] executeInsert(
            Connection connection,
            final Dao dao,
            final Entity entity,
            final List list,
            final SimpleSqlBuilder builder,
            boolean output) throws SQLException {

        //data一定要有值

        Object data = list.get(0);

        EntitySqlUtils.buildInsert(
                builder,
                dao.getDriver(),
                entity,
                data,
                null,
                false);


        PreparedStatement ps = null;
        try {
            ps = entity.prepareInsert(connection, builder.sql.toString());
            for (int i = 0, c = list.size(); i < c; ++i) {
                data = list.get(i);
                builder.clear(true);
                EntitySqlUtils.buildInsert(
                        builder,
                        dao.getDriver(),
                        entity,
                        data,
                        null,
                        false);
                EntityActiveRecordUtils.prepareStatement(ps, builder, output);
                ps.addBatch();

            }
            int[] counts = ps.executeBatch();
            ps.clearBatch();
            return counts;
        } finally {
            builder.clear(true);
            DaoUtils.close(ps);
        }

    }
}
